package com.dianjing.dianqun.common.shiro;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.dianjing.dianqun.dao.dianpai.DianQunUserMapper;
import com.dianjing.dianqun.model.DianQunUser;
import com.dianjing.dianqun.utils.AESUtil;

@Configuration
public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private DianQunUserMapper userMapper;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username =(String) principals.getPrimaryPrincipal();
		DianQunUser user = userMapper.getUserByLoginName(username);
		if(user!=null) {
			SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
			// 根据用户名查询当前用户拥有的角色
			String[] roles = user.getRole().split(",");
			Set<String> roleNames = new HashSet<String>(Arrays.asList(roles));
			// 将角色名称提供给info
			authorizationInfo.setRoles(roleNames);
			return authorizationInfo;
		}
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken passwordToken=(UsernamePasswordToken)token;
		DianQunUser user = userMapper.getUserByLoginName(passwordToken.getUsername());
		if(null!=user) {
			String decode = AESUtil.AESEncode(String.valueOf(passwordToken.getPassword()));
			if(decode.equals(user.getPassword())) {
				return new SimpleAuthenticationInfo(user.getUsername(), passwordToken.getPassword(), getName());
			}
		}
//		throw new UnauthenticatedException("登录失败");
		return  null;
	}

}
